<?php

namespace Pinenut\User\OAuth2;

use \Pinenut\User\OAuth2\Config as Config;

/**
 * Обработчик oauth2 входа и регистрации
 *
 * @author kosh
 *        
 */
trait Auth {
	
	abstract function config ();
		
	protected function auth() {
		if ($this->request->onlyRender)  
			return ;
		$config = $this->config();

		// осуществеление аутетинфикации
		$client = new \OAuth2\Client ( $config[Config::CLIENTID], $config[Config::CLIENTSECRET] );
		if (!$this->request->code) {
			$auth_url = $client->getAuthenticationUrl ( $config[Config::AUTHORIZEURL],
					$config[Config::REDIRECTURL], ['scope'=>$config[Config::SCOPE]] );
			$this->redirect ( $auth_url );
		} else {
			$params = array (
					'code' => $this->request->code,
					'redirect_uri' => $config[Config::REDIRECTURL]
			);
			
			$response = $client->getAccessToken ( $config[Config::TOKENURL], 'authorization_code', $params );

			if (200 == $response ['code'] ) {
				if (is_string($response ['result'])) {
					parse_str ( $response ['result'], $info );
				} else {
					$info = $response ['result'];
				}
				return $this->createAuth($info);
			}
				
		}
	}

	abstract function createAuth($data);
}